package servlet.product;

import bean.pojo.Products;
import com.alibaba.fastjson2.JSONObject;
import commons.baseServlet.BaseServlet;
import commons.format.NumberFormat;
import commons.r.R;
import org.apache.commons.math3.stat.descriptive.summary.Product;
import service.ProductService;
import service.impl.ProductServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * servlet.product
 * User: 李雨行
 * Date: 2024/12/17 15:19
 * motto:   沉淀哥
 * Description:
 * Version: V1.0
 */
@WebServlet(value = "/product/*")
public class ProductServlet extends BaseServlet {
    public R findByPage(HttpServletRequest request){
        Integer productId= NumberFormat.stringToInteger(request.getParameter("productId"));
        Integer page= NumberFormat.stringToInteger(request.getParameter("page"));
        Integer limit= NumberFormat.stringToInteger(request.getParameter("limit"));
        String productName=request.getParameter("productName");
        String productCategory=request.getParameter("productCategory");
        ProductService productService=new ProductServiceImpl();
        List<Products> list=productService.findByPage(productId,productName,productCategory,page,limit);
        Integer maxPage=productService.maxPage(productId,productName,productCategory);
        return list.size()>0?R.ok().addData("total",maxPage).addData("data",list):R.error("没有数据");
    }
    public R add(HttpServletRequest request){
        try {
            BufferedReader bufferedReader=request.getReader();
            String data=bufferedReader.readLine();
            Products products= JSONObject.parseObject(data,Products.class);
            ProductService productService=new ProductServiceImpl();
            boolean t=productService.add(products);
            return t?R.ok("添加成功"):R.ok("添加失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("添加出错");
    }
    public R deleteById(HttpServletRequest request){
        Integer id=NumberFormat.stringToInteger(request.getParameter("productId"));
        ProductService productService=new ProductServiceImpl();
        return productService.deleteById(id)?R.ok("删除成功"):R.ok("删除失败");
    }
    public R update(HttpServletRequest request){
        try {
            BufferedReader bufferedReader=request.getReader();
            Products products=JSONObject.parseObject(bufferedReader.readLine(),Products.class);
            ProductService productService=new ProductServiceImpl();
            return productService.update(products)?R.ok("修改成功"):R.ok("修改失败");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("修改失败");
    }
}
